package com.sky.item.controller;


import com.sky.constant.ESConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.item.mq.producer.DishProducer;
import com.sky.item.service.DishService;
import com.sky.item.service.es.DishServiceForES;
import com.sky.item.service.es.DishVOForES;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin/dish")
@Api(tags = "菜品相关")
@RequiredArgsConstructor
@Slf4j
public class DishController {

    private final DishService dishService;
    private final RedisTemplate redisTemplate;

    private final DishServiceForES dishServiceForES;

    private final DishProducer dishProducer;

    private final DishVOForES dishVOForES;

    /**
     * 新增菜品
     * @param dishDTO
     * @return
     */
    @PostMapping
    @ApiOperation("新增菜品")
    public Result add(@RequestBody DishDTO dishDTO){
        log.info("新增菜品:{}",dishDTO.getName());

        dishService.saveDishWithFlavor(dishDTO);
//        log.info("insert into es:id="+dishDTO.getId()+" name = "+dishDTO.getName());
//        dishProducer.send(dishDTO.getId(),dishDTO.getName(), ESConstant.INSERT_ES);
        return Result.success();
    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     * @return
     */
    @GetMapping("/page")
    @ApiOperation("分页查询菜品")
    public Result<PageResult> pageList(DishPageQueryDTO dishPageQueryDTO) throws IOException {
        log.info("分页查询菜品");

        PageResult pageResult = dishService.pageList(dishPageQueryDTO);

        return Result.success(pageResult);
    }

    /**
     * 批量删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result deleteBatch(@RequestParam(value = "ids") List<Long> ids){
        log.info("批量删除菜品");

        dishService.deleteBatch(ids);
        for (Long id : ids) {
            log.info("delete from es:id="+id);
            dishProducer.send(id,"",ESConstant.DELETE_ES);
        }
        return Result.success();
    }

    /**
     * 根据id查询菜品VO
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    @ApiOperation("根据id查询菜品VO")
    public Result<DishVO> getDishVOById(@PathVariable Long id){
        log.info("根据id查询菜品VO");
        DishVO dishVO = dishVOForES.findById(id);
//        DishVO dishVO = dishService.getDishVOById(id);
        return Result.success(dishVO);
    }


    @GetMapping("/name/{name}")
    @ApiOperation("根据菜名查询菜品VO")
    public Result<List<DishVO>> getDishVOByName(@PathVariable String name) throws IOException {
        log.info("根据菜名:["+name+"]查询菜品VO");
        Boolean optimize = true;
        List<DishVO> dishVOList = null;
        long start = System.nanoTime();
        if(optimize){
            //1.使用es优化的查询
            List<Long> ids = dishServiceForES.searchByName(name);
            dishVOList = new ArrayList<>();
            for (Long id : ids) {
                log.info("id = "+id);
                DishVO dishVO = dishService.getDishVOById(id);
                dishVOList.add(dishVO);
            }
            // optimaze status is true : use 50883250 ns
        }
        else {
            //2.未使用es优化
            dishVOList = dishService.getDishVOByName(name);
            // optimaze status is false : use 30076625 ns
        }
        long end = System.nanoTime();
        log.info("optimaze status is "+optimize+" : use "+(end-start)+" ns");
        return Result.success(dishVOList);
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    @ApiOperation("修改菜品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        log.info("修改菜品");
        dishService.updateDish(dishDTO);
        dishProducer.send(dishDTO.getId(),dishDTO.getName(),ESConstant.UPDATE_ES);
        log.info("update into es:id="+dishDTO.getId()+" name = "+dishDTO.getName());
        redisTemplate.delete(redisTemplate.keys("dish_*"));
        return Result.success();
    }


    /**
     * 菜品启停售
     * @param status
     * @param id
     * @return
     */
    @PostMapping("/status/{status}")
    @ApiOperation("菜品启停售")
    public Result startOrStop(@PathVariable Integer status,Long id){

        log.info("菜品启停售");
        dishService.startOrStop(status,id);
        if (status.equals(StatusConstant.ENABLE)){
            DishVO dishVO = dishService.getDishVOById(id);
            log.info("insert into es:id="+id+" name = "+dishVO.getName());
            dishProducer.send(id,dishVO.getName(),ESConstant.INSERT_ES);
        }
        else {
            log.info("delete from es:id="+id);
            dishProducer.send(id,"",ESConstant.DELETE_ES);
        }
        // 为了省事，直接清除所有菜品分类的缓存
        // redisTemplate.keys(String pattern) 根据指定的匹配模式pattern来列举出所有匹配到的key
        redisTemplate.delete(redisTemplate.keys("dish_*"));

        return Result.success();
    }

    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<Dish>> getByCategoryId(Long categoryId){
        log.info("根据分类id查询菜品");
        List<Dish> dishList = dishService.getByCategoryId(categoryId);
        return Result.success(dishList);
    }

}
